<template lang="pug">
div.register-page
  div.login-box
    div.row.logo-wrapper
      img.logo(src='../assets/logo_mono.svg')
      div.pull-right(style='font-size: 16px')
        span 已有账号？
        router-link(to='/login') 登录
    div.row.step-wrapper
      div.step
        span.line
        Steps(:current='current')
          Step(title="1.填写手机号码")
          Step(title="2.完善登录信息")
          Step(title="3.注册成功")
    Card.login-card(shadow)
      Alert.login-errors(type='error', v-if='errMsg')
        p(v-for='(msg, idx) in errMsg', v-html='msg')
      div.form-wrapper
        Form(ref='form', :model='formData', :label-width="100", :rules='rules' action='javascript:;')
          FormItem(prop='name', label='手机号码' v-if='current == 0')
            Input(type='text', v-model='formData.name', :disabled='freeze', name='phone', autocomplete='on')
              span.phone-prefix(slot='prepend') + 86
          FormItem(prop='code', label='验证码' class="register-input-left" v-if='current == 0')
            Input(type='text', v-model='formData.code', name='code')
              //- Icon(style='width: 16px', type='ios-locked-outline', slot='prepend')
              CountDownButton(
                class='count-down-button'
                slot='append'
                :countDown=60
                :ready-label='countDownLabel'
                counting-label='重新获取短信 (%count)'
                :before-click='requestSms'
                @count-down-end='onCountDownEnd')
            p(v-show='showSmsHelp', style='padding-top: 6px') 验证码发送成功，60秒内未收到请重新获取
            p(v-show='showSmsError') 验证码发送失败，请重试
          div(v-if='current === 1')
            FormItem(prop='mail', label='邮箱')
              Input(type='text', v-model='formData.mail', name='email', autocomplete='on')
            FormItem(prop='app', label='APP名称')
              Input(type='text', v-model='formData.app', name='app', autocomplete='on')
            FormItem(prop='pass', label='密码')
              Input(type='password', v-model='formData.pass', name='pass')
            FormItem(prop='confirmPass', label='确认密码')
              Input(type='password', v-model='formData.confirmPass', name='comfirmpass')
          div.success-icon( v-show='current == 2')
            span.text 注册成功
            div.icon-inner
              span.icon
          div.next-step-wrapper
            Button(type='primary', @click='next', :loading='processing' v-show='this.current < 2') 下一步
          span.time(v-show='this.current == 2') {{ time }} 秒后进入管理中心
</template>

<script>
import CountDownButton from '@/components/CountDownButton'
import Api from '@/apis/app'
import userApi from '@/apis/user'

export default {
  components: {
    CountDownButton
  },
  data () {
    return {
      current: 0,
      errMsg: null,
      freeze: false,
      processing: false,
      countDownLabel: '发送短信验证码',
      showSmsHelp: false,
      showSmsError: false,
      codeValidated: false,
      time: '5',
      formData: {
        name: '',
        mail: '',
        pass: '',
        confirmPass: '',
        app: '',
        code: ''
      },
      rules: {
        name: [
          // { type: 'number', required: true, message: '请填写手机号码' },
          {
            message: '请输入有效手机号码',
            trigger: 'blur',
            validator (rule, value, next) {
              if (/^1\d{10,10}$/.test(value)) {
                next()
              } else {
                next(rule.message)
              }
            }
          },
          {
            message: '该手机已注册',
            trigger: 'blur',
            validator (rule, value, next) {
              if (!value) {
                return next()
              }
              userApi.search(value).then((data) => {
                const idx = data.findIndex(item => item.name === value)
                idx > -1 ? next(rule.message) : next()
              })
            }
          }
        ],
        code: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          {
            message: '验证码错误',
            trigger: 'submit',
            validator: (rule, value, next) => {
              if (!value) {
                return next()
              }
              Api.validateCode(this.formData).then((data) => {
                data.errCode ? next(rule.message) : next()
              })
            }
          }
        ],
        pass: { type: 'string', required: true, /* min: 6, */ message: '请输入密码', trigger: 'blur' },
        confirmPass: [
          { type: 'string', required: true, message: '请再次输入密码', trigger: 'blur' },
          {
            trigger: 'blur',
            validator: (rule, value, next) => {
              if (value === '') {
                return next(rule.message)
              } else if (value !== this.formData.pass) {
                return next('两次输入的密码不一致')
              } else {
                return next()
              }
            }
          }
        ],
        mail: [
          { required: true, message: '请填写邮箱地址' },
          { type: 'email', required: true, message: '请填写正确的邮箱地址', trigger: 'blur' },
          {
            message: '该邮箱已注册',
            trigger: 'submit',
            validator (rule, value, next) {
              if (!value) {
                return next()
              }

              Api.searchMail(value).then(data => {
                data ? next(rule.message) : next()
              })
            }
          }
        ],
        app: [
          { type: 'string', required: true, message: '请填写APP名称' },
          {
            message: '该名称已注册',
            trigger: 'submit',
            validator (rule, value, next) {
              if (!value) {
                return next()
              }
              Api.searchApp({ app_name: value }).then((data) => {
                data ? next(rule.message) : next()
              })
            }
          }
        ]
      }
    }
  },
  methods: {
    create () {
      this.processing = true
      this.$refs.form.validate(valid => {
        if (valid) {
          Api.createApp(this.formData).then(data => {
            if (data.errCode === 201) {
              // this.$router.replace('/settings')
              // 注册成功5秒后跳转
              this.current = 2
              setInterval(() => {
                this.time = this.time - 1
              }, 1000)
              setTimeout(function () {
                window.location.href = '/'
              }, 5000)
            } else {
              this.errMsg = data.errMsg
            }
            this.processing = false
          })
        } else {
          console.log('form not validated')
          this.processing = false
        }
      })
    },
    async requestSms () {
      let valid = await new Promise(resolve => {
        this.$refs.form.validateField('name', (err) => {
          if (err) {
            resolve(false)
          } else {
            resolve(true)
          }
        })
      })

      if (!valid) return false

      try {
        this.showSmsError = false
        // this.freeze = true
        await Api.requestCodeSms(this.formData.name)
        this.showSmsHelp = true
      } catch (e) {
        // this.countDownLabel
        this.showSmsError = true
        // this.freeze = false
        return false
      }
    },
    onCountDownEnd () {
      // this.freeze = false
      this.countDownLabel = '重新获取短信验证码'
    },
    next () {
      if (this.current === 0) {
        this.processing = true
        this.$refs.form.validate(valid => {
          valid && this.current++
          this.processing = false
        })
      }

      if (this.current === 1) {
        this.create()
      }
    }
  }
}
</script>

<style lang="less">
.register-page {
  width: 100%;
  height: 100%;
  background-color: #e6e6e6;
  position: relative;
  .login-box {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);

    h1, h2 {
      margin-bottom: 8px;
    }
  }
  .login-card {
    width: 1150px;
  }
  .logo-wrapper {
    padding: 20px 20px;
    background-color: #fff;
    border-bottom: 1px solid #f4f4f4;

    .logo {
      height: 35px;
      width: auto;
    }
  }
}

  .form-wrapper {
    width: 440px;
    margin: 70px auto;
    .ivu-input-group-prepend {
      background-color: #fff;
    }
    .ivu-form-item-label {
      font-size: 14px;
      padding-top: 11px;
      padding-bottom: 11px;
    }
    .phone-prefix {
      display: inline-block;
      width: 60px;
      background-color: #fff;
    }
    input {
      height: 36px;
    }
    .register-input-left {
      border-spacing: 5px 0;
      .ivu-input {
        border-radius: 4px;
        position: relative;
        right: 5px;
      }
      .ivu-input-group-append {
        background-color: transparent;
        border: none;
        border-radius: 4px;
        border-bottom-left-radius: 4px!important;
        border-top-left-radius: 4px!important;
        position: relative;
        left: 5px;
        .count-down-button {
          color: #fff;
        }
        .ivu-btn-ghost {
          color: #fff;
          background-color: #377dff;
        }
        .ivu-btn-ghost[disabled] {
          color: #898a8c;
          background-color: #f7f7f7;
          border-color: #dddee1;
        }
      }
      &.ivu-form-item-error {
        .ivu-input-group-append {
          border: none;
        }
      }
    }
    .time {
      display: block;
      margin: 0 auto;
      text-align: center;
      font-weight: 600;
      opacity: 0.8;
    }
  }
  .next-step-wrapper {
    padding-left: 100px;
    margin-top: 50px;
    .ivu-btn {
      width: 85px;
      background-color: #377dff;
      font-size: 14px;
    }
    .ivu-btn[disabled] {
      color: #bbbec4;
      background-color: #f7f7f7;
      border-color: #dddee1;
    }
  }
  .login-errors {
    margin-bottom: 24px;
  }
  .success-icon {
    width: 110px;
    height: 110px;
    margin: 0 auto;
    margin-bottom: 115px;
    position: relative;
    border: 2px solid #d1e7fe;
    border-radius: 73px;
    .icon-inner {
      background-color: #377dff;
      width: 90px;
      height: 90px;
      position: absolute;
      top: 8px;
      left: 8px;
      border-radius: 65px;
      text-align: center;
      .icon {
        color: #fff;
        font-size: 100px;
        font-weight: 600;
        line-height: 90px;
        font-family: Ionicons;
        &:before {
          content: "\F3FD";
        }
      }
    }
    .text {
      display: block;
      position: absolute;
      width: 146px;
      text-align: center;
      top: 130px;
      font-size: 24px;
      left: 50%;
      margin-left: -73px;
    }
  }
  .step-wrapper {
    height: 150px;
    background-color: #fff;
    border-bottom: 1px solid #f4f4f4;
    text-align: center;
    .step {
      display: inline-block;
      width: 80%;
      margin: 50px auto;
      position: relative;
      .ivu-steps-head-inner>.ivu-steps-icon {
        line-height: 30px;
      }
      .line {
        height: 40px;
        width: 820px;
        background: url('../assets/step-line.png') no-repeat;
        background-size: 100% 100%;
        display: block;
        position: absolute;
        top: -5px;
        z-index: 1;
        left: 50%;
        margin-left: -410px;
      }

    }

    .ivu-steps-item {
      z-index: 2;
      text-align: center;
      &.ivu-steps-status-process {
        .ivu-steps-head-inner {
          background-color: #0982f6;
          span {
            color: #fff;
          }
        }
      }
      .ivu-steps-tail {
        display: none;
      }
      .ivu-steps-head-inner {
        width: 30px;
        height: 30px;
        line-height: 30px;
        position: relative;
        background-color: #d1e7fe;
        border: none;
        span {
          color: #0070f4;
          font-weight: 600;
        }
        &:after {
          content: '';
          display: block;
          position: absolute;
          width: 38px;
          height: 38px;
          border: 1px solid #d1e7fe;
          top: -4px;
          left: -4px;
          border-radius: 19px;
        }
      }
      .ivu-steps-main {
        display: block;
        position: relative;
        text-align: center;
        margin-top: 10px;
        left: -5px;

      }
      .ivu-steps-title {
        margin-top: 6px;
        display: inline-block;
        padding-right: 0;
      }
    }
  }
</style>
